﻿using UnityEngine;
using UnityEditor;

public class CommonSkillAction : ISkillAction
{
    private int targetId;

    private float runTime = 0;

    public CommonSkillAction(OwnerObj ownerObj) : base(ownerObj)
    {

    }

    /// <summary>
    /// 掉血
    /// </summary>
    /// <param name="targetUnitObj"></param>
    public override void DoDamage(IUnitObject targetUnitObj)
    {
        // 处理伤害
        if (null == targetUnitObj)
        {
            return;
        }

        // 处理掉血
        int damageHp = Random.Range(10, 20);

        IUnitObject unitObj = ownerObj.Get<IUnitObject>();
        targetUnitObj.GetModule().Get<ModAttr>().LossHp(damageHp, unitObj);
    }

    public override void Interrupt()
    {
        
    }

    public override bool IsCanInterrupt(IAction nextAction)
    {
        return false;
    }

    public override bool IsFinished()
    {
        return (ESkillState.Finish == eSkillState);
    }

    public override void SetTarget(int targetId)
    {
        this.targetId = targetId;
    }

    public override void Load()
    {
        eSkillState = ESkillState.Run;

        // 攻击开始
        AllEvent.eventAttack.Fire(ownerObj.Get<IUnitObject>(), true);

        // 调整攻击朝向
        UnityGameObject unityGameObject = ownerObj.Get<IUnitObject>().GetUnityGameObject();
        if (null == unityGameObject)
        {
            return;
        }

        IUnitObject targetUnitObj = ownerObj.Get<IUnitObject>().GetStage().GetObj<IUnitObject>(targetId);
        if (null != targetUnitObj)
        {
            if (ownerObj.Get<IUnitObject>().GetPosition().x < targetUnitObj.GetPosition().x)
            {
                unityGameObject.SetRotation(Quaternion.Euler(0, 180, 0));
            }
            else
            {
                unityGameObject.SetRotation(Quaternion.Euler(0, 0, 0));
            }
        }
    }

    public override void Unload()
    {
        // 攻击结束
        AllEvent.eventAttack.Fire(ownerObj.Get<IUnitObject>(), false);
    }

    public override void Update(float deltaTime)
    {
        if (ESkillState.Run == eSkillState)
        {
            runTime += deltaTime;

            if (runTime >= 0.6)
            {
                // 攻击
                IUnitObject targetUnitObj = ownerObj.Get<IUnitObject>().GetStage().GetObj<IUnitObject>(targetId);
                if (null != targetUnitObj)
                {
                    DoDamage(targetUnitObj);
                }

                eSkillState = ESkillState.waitFinish;
            }
        }
        else if (ESkillState.waitFinish == eSkillState)
        {
            //等待结束
            runTime += deltaTime;

            if (runTime > 1)
            {
                eSkillState = ESkillState.Finish;
            }
        }
    }
}